#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <string.h>
#include <cstdlib>
#include <memory>
#include <functional>
#include "nocopy.hpp"
#include "InetAddr.hpp"
#include "Common.hpp"
#include "Log.hpp"
using namespace LogModule;
const static int defaultport = 8888;
const static int defaultsockfd = -1;
const static int defaultsize = 1024;

using func_tt = std::function<void(int sockfd,const std::string&,InetAddr&)>;

// 禁止拷贝和赋值
class UdpServer : public NoCopy
{
public:
    UdpServer(func_tt func,uint16_t port = defaultport) : _port(port), _sockfd(defaultsockfd),_func(func)
    {
    }

    void Init()
    {
        // 1.创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error...";
            exit(SOCKET_ERR);
        }
        LOG(LogLevel::DEBUG) << "sockfd success: " << _sockfd;

        // 2.初始化结构体
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        //memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;//注意这里不要写特定的ip值
        local.sin_port = htons(_port);
        // 3.bind，结构体填完，还要设置到内核中
        int n = ::bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n!=0)
        {
            LOG(LogLevel::FATAL) << "bind error...";
            exit(BIND_ERR);
        }
        LOG(LogLevel::DEBUG) << "bind success...";

    }
    void Start()
    {
        while(true)
        {
            char buffer[defaultsize];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            
            ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&peer,&len);
            if(n > 0)
            {
                InetAddr addr(peer);
                buffer[n] = 0;
                _func(_sockfd,buffer,addr);//路由功能，外部传函数
            }
        }
    }

    ~UdpServer()
    {
    }

private:
    //std::string _ip;
    uint16_t _port;
    int _sockfd;

    func_tt _func;
};